package com.masterlu.leetcode.daily.stack.simple;

import java.util.Stack;

/**
 * 1047. 删除字符串中的所有相邻重复项
 * https://leetcode-cn.com/problems/remove-all-adjacent-duplicates-in-string/
 */
public class S1047RemoveDuplicates {

    public String removeDuplicates(String s) {
        //1.将字符串，这个存储在栈中。（在储存时，取出栈中数据进行比较。如果相同则清理栈中数据）
        Stack<Character> finalStack = new Stack<>();
        for (char c : s.toCharArray()) {
            if (finalStack.isEmpty()) {
                finalStack.push(c);
            } else {
                if (finalStack.peek() == c) {
                    finalStack.pop();
                } else {
                    finalStack.push(c);
                }
            }
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (Character character : finalStack) {
            stringBuilder.append(character);
        }

        return stringBuilder.toString();
    }

    public String removeDuplicates2(String s) {
        //1.将字符串，这个存储在栈中。（在储存时，取出栈中数据进行比较。如果相同则清理栈中数据）

        StringBuilder finalStr = new StringBuilder();
        for (char c : s.toCharArray()) {
            if (finalStr.length() == 0) {
                finalStr.append(c);
            } else {
                if (finalStr.charAt(finalStr.length() - 1) == c) {
                    finalStr.setLength(finalStr.length() - 1);
                } else {
                    finalStr.append(c);
                }
            }
        }

        return finalStr.toString();
    }
}
